<template>
  <div class="admin-app-page">
    <!-- 搜索卡片 -->
    <div class="search-card">
      <a-form
        layout="inline"
        :model="formSerchParams"
        @submit="doSerach"
        class="search-form"
      >
        <a-form-item field="appName" label="应用名" class="form-item">
          <a-input
            allow-clear
            v-model="formSerchParams.appName"
            placeholder="请输入应用名称"
            class="search-input"
          />
        </a-form-item>

        <a-form-item field="appDesc" label="应用简介" class="form-item">
          <a-input
            allow-clear
            v-model="formSerchParams.appDesc"
            placeholder="请输入应用描述"
            class="search-input"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" class="search-btn">
            <template #icon>
              <icon-search />
            </template>
            搜索
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-card">
      <a-table
        :columns="columns"
        :data="dataList"
        :pagination="pagination"
        :row-class="setRowClass"
        @page-change="onPageChange"
        row-key="id"
      >
        <!-- 应用图标 -->
        <template #appIcon="{ record }">
          <a-avatar :size="40" shape="square">
            <img :src="record.appIcon" alt="应用图标" />
          </a-avatar>
        </template>

        <!-- 类型映射 -->
        <template #appType="{ record }">
          <a-tag color="arcoblue" size="small">
            {{ APP_TYPE_MAP[record.appType] }}
          </a-tag>
        </template>

        <!-- 评分策略 -->
        <template #scoringStrategy="{ record }">
          <a-tag color="purple" size="small">
            {{ APP_SCORING_STRATEGY_MAP[record.scoringStrategy] }}
          </a-tag>
        </template>

        <!-- 审核状态 -->
        <template #reviewStatus="{ record }">
          <a-tag
            :color="getStatusColor(record.reviewStatus)"
            size="small"
            bordered
          >
            {{ REVIEW_STATUS_MAP[record.reviewStatus] }}
          </a-tag>
        </template>

        <!-- 时间格式化 -->
        <template #time="{ record }">
          <span v-if="record.reviewTime">
            {{ dayjs(record.reviewTime).format("YYYY-MM-DD") }}
          </span>
          <span v-else>-</span>
        </template>

        <!-- 用户名（从user对象获取） -->
        <template #userName="{ record }">
          <div class="user-info">
            <a-avatar :size="24" :image-url="record.user?.userAvatar" />
            <span class="user-name">{{ record.user?.userName || "-" }}</span>
          </div>
        </template>

        <!-- 操作列 -->
        <template #optional="{ record }">
          <a-button
            v-if="record.reviewStatus !== REVIEW_STATUS_ENUM.PASS"
            status="success"
            @click="doReview(record, REVIEW_STATUS_ENUM.PASS, '')"
          >
            通过
          </a-button>

          <a-button
            v-if="record.reviewStatus !== REVIEW_STATUS_ENUM.REJECT"
            status="warning"
            @click="showRejectModal(record)"
          >
            拒绝
          </a-button>

          <a-popconfirm
            content="确认要删除该应用吗？"
            type="error"
            @ok="doDelete(record)"
          >
            <a-button status="danger"> 删除 </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </div>

    <!-- 拒绝理由弹窗 -->
    <a-modal
      v-model:visible="rejectModal.visible"
      title="输入拒绝理由"
      @ok="handleReject"
      @cancel="rejectModal.visible = false"
      class="reject-modal"
    >
      <a-textarea
        v-model="rejectModal.reason"
        placeholder="请输入拒绝理由..."
        :rows="3"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from "vue";
import { API } from "@/api/typings";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import {
  deleteAppUsingPost,
  doAppReviewUsingPost,
  listAppVoByPageUsingPost,
} from "@/api/appController";
import {
  APP_SCORING_STRATEGY_MAP,
  APP_TYPE_MAP,
  REVIEW_STATUS_ENUM,
  REVIEW_STATUS_MAP,
} from "../../constant/app";

// 初始化搜索条件
const initSearchParams = {
  current: 1,
  pageSize: 10,
};

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50],
});

// 拒绝弹窗状态
const rejectModal = reactive({
  visible: false,
  currentRecord: null as API.App | null,
  reason: "",
});

// 显示拒绝弹窗
const showRejectModal = (record: API.App) => {
  rejectModal.currentRecord = record;
  rejectModal.visible = true;
};

// 处理拒绝操作
const handleReject = () => {
  if (rejectModal.currentRecord) {
    doReview(
      rejectModal.currentRecord,
      REVIEW_STATUS_ENUM.REJECT,
      rejectModal.reason
    );
    rejectModal.visible = false;
    rejectModal.reason = "";
  }
};

// 根据状态获取标签颜色
const getStatusColor = (status: number) => {
  switch (status) {
    case REVIEW_STATUS_ENUM.PASS:
      return "green";
    case REVIEW_STATUS_ENUM.REJECT:
      return "red";
    default:
      return "gray";
  }
};

// 设置表格行样式（斑马纹）
const setRowClass = (record: API.App, index: number) => {
  return index % 2 === 1 ? "stripe-row" : "";
};

// 执行搜索
const doSerach = () => {
  serachParame.value = {
    ...initSearchParams,
    ...formSerchParams.value,
  };
};

const formSerchParams = ref<API.AppQueryRequest>({});

const serachParame = ref<API.AppQueryRequest>({
  ...initSearchParams,
});

const dataList = ref<API.App[]>([]);

const total = ref<number>(0);

/**
 * 加载数据
 */
const loadData = async () => {
  const res = await listAppVoByPageUsingPost(serachParame.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
    pagination.total = total.value;
  } else {
    message.error("获取数据失败", res.data.message);
  }
};

/**
 * 分页变化时重新加载数据
 * @param page 当前页码
 */
const onPageChange = (page: number) => {
  serachParame.value = {
    ...serachParame.value,
    current: page,
  };
};

/**
 * 删除应用
 * @param record 应用记录
 */
const doDelete = async (record: API.App) => {
  if (!record.id) {
    return;
  }

  const res = await deleteAppUsingPost({
    id: record.id,
  });
  if (res.data.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除应用失败", res.data.message);
  }
};

// 监听搜索参数变化自动加载数据
watchEffect(() => {
  loadData();
});

/**
 * 执行审核操作
 * @param record 应用记录
 * @param reviewStatus 审核状态
 * @param reviewMessage 审核信息
 */
const doReview = async (
  record: API.App,
  reviewStatus: number,
  reviewMessage?: string
) => {
  if (!record.id) {
    return;
  }
  const res = await doAppReviewUsingPost({
    id: record.id,
    reviewStatus,
    reviewMessage,
  });

  if (res.data.code === 0) {
    message.success(
      reviewStatus === REVIEW_STATUS_ENUM.PASS ? "审核通过" : "已拒绝"
    );
    loadData();
  } else {
    message.error("审核失败" + res.data.message);
  }
};

// 表格列配置
const columns = [
  {
    title: "应用名",
    dataIndex: "appName",
    width: 180,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "应用描述",
    dataIndex: "appDesc",
    width: 200,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "应用图标",
    dataIndex: "appIcon",
    slotName: "appIcon",
    width: 80,
    align: "center",
  },
  {
    title: "应用类型",
    dataIndex: "appType",
    slotName: "appType",
    width: 100,
    align: "center",
  },
  {
    title: "评分策略",
    dataIndex: "scoringStrategy",
    slotName: "scoringStrategy",
    width: 100,
    align: "center",
  },
  {
    title: "审核状态",
    dataIndex: "reviewStatus",
    slotName: "reviewStatus",
    width: 100,
    align: "center",
  },
  {
    title: "审核信息",
    dataIndex: "reviewMessage",
    width: 150,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "审核时间",
    slotName: "time",
    width: 120,
    align: "center",
  },
  {
    title: "用户名",
    slotName: "userName",
    width: 120,
  },
  {
    title: "操作",
    slotName: "optional",
    width: 180,
    align: "center",
  },
];
</script>

<style scoped>
.admin-app-page {
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
}

.search-card {
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 4px;
}

.search-form {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  align-items: center;
}

.form-item {
  margin-right: 0;
  margin-bottom: 0;
}

.form-item .arco-form-item-label {
  font-weight: 500;
}

.search-input {
  width: 200px;
}

.search-btn {
  border-radius: 4px;
}

.table-card {
  background-color: var(--color-bg-2);
  border-radius: 4px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

.table-card .arco-table-tr {
  transition: background-color 0.2s;
}

.table-card .arco-table-tr:hover {
  background-color: var(--color-fill-1) !important;
}

.table-card .stripe-row {
  background-color: var(--color-fill-1);
}

.table-card .arco-table-th {
  background-color: var(--color-fill-1);
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  border-radius: 4px;
}

.reject-modal .arco-modal-content {
  padding: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

@media (max-width: 768px) {
  .search-input {
    width: 160px;
  }

  .table-card {
    overflow-x: auto;
  }

  .action-buttons {
    gap: 4px;
  }
}
</style>
